package cn.fancy.sdk.login.utils;

import static cn.fancy.sdk.config.FileDir.ACCOUNTS_PASSWORDS_FILE2;

import android.content.Context;
import cn.fancy.sdk.FancyManager;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Collections;

import android.os.Environment;
import android.util.Log;
import android.util.Pair;
import cn.fancy.sdk.common.utils.DevUtil;
import cn.fancy.sdk.common.utils.Logger;
import cn.fancy.sdk.common.utils.SE;
import cn.fancy.sdk.config.FileDir;

public class AccountHelper {

	public static int ACCOUNT_VALID = 1;
	public static int ACCOUNT_INVALID = 0;

	public static Local_Account getLastestLoginAccountFromOldSdk(Context context) {

		Pair<String, String> ac = DevUtil.getAccountFromSDcard_old(context);

		Local_Account acct = new Local_Account();

		if (ac != null) {

			acct.username = ac.first;
			acct.password = ac.second;

			Logger.print_red("getAccount(...) - ",
					"Account from old account file");

		}

		return acct;
	}

	/**
	 * 
	 * 更新本地全局账号
	 * 
	 * @param lacct
	 */
	public static void updateLocalAccounts( Local_Account lacct) {

		Context context = FancyManager.getInstance().getmContext();

		String username = lacct.username;
		String password = lacct.password;
		int isValid = lacct.isValid;
		long last_login_time = lacct.last_login_time;

		ArrayList<Local_Account> accts = getLocalAccountsAsArrayList(context, false);

		// 先检查该账号是否已经存在
		boolean isAccountPresents = false;
		int i;
		for (i = 0; i < accts.size(); i++) {
			Local_Account temp = accts.get(i);

			// 账号已经在本地文件中，更新内容
			if (temp.username.equalsIgnoreCase(username)) {

				temp.isValid = isValid;

				temp.password = password;

				if (last_login_time != 0) {
					temp.last_login_time = last_login_time;
				}

				isAccountPresents = true;

				break;
			}
		}

		// 新账号插入
		if (!isAccountPresents) {
			accts.add(new Local_Account(username, password, isValid,
					last_login_time));
		}

		// 按登录时间进行递增排序
		Collections.sort(accts);

		// 将所有账号重新存入文件中
		try {
			File file = new File(context.getFilesDir() + ACCOUNTS_PASSWORDS_FILE2);
//			File file = new File(Environment.getExternalStorageDirectory()
//					.getAbsoluteFile() + FileDir.ACCOUNTS_PASSWORDS_FILE);

			File parent = file.getParentFile();
			if (!parent.exists())
				parent.mkdirs();

			if (file.exists())
				file.delete();
			file.createNewFile();

			FileOutputStream writer = new FileOutputStream(file);

			byte[] plain_bytes;
			byte[] encrypted_bytes;
			String content = "";

			// 开始组装字符串
			for (int j = 0; j < accts.size(); j++) {
				Local_Account acct = accts.get(j);

				if (j == (accts.size() - 1)) {
					content += acct.username + ":" + acct.password + ":"
							+ acct.isValid + ":" + acct.last_login_time;
				} else {
					content += acct.username + ":" + acct.password + ":"
							+ acct.isValid + ":" + acct.last_login_time + ",";
				}
			}

			Logger.print_red("updateLocalAccounts(...) accounts= " + content);

			plain_bytes = content.getBytes("utf-8");

			// 加密输出到文件
			encrypted_bytes = SE.getInstance().encrypt(plain_bytes);
			writer.write(encrypted_bytes);
			writer.flush();
			writer.close();

		} catch (Exception e) {
			Logger.print_red(e.getLocalizedMessage());
		}

	}

	/**
	 * 获取本地文件系统中保存的所有用户名和密码
	 * 
	 * @param valid_only
	 *            若只想获得有效用户账号则为true，若想获得所有用户账号则为false
	 * @return 如果没有记录返回空ArrayList而不是null
	 */
	public static ArrayList<Local_Account> getLocalAccountsAsArrayList(Context context, final boolean valid_only) {

		ArrayList<Local_Account> accounts = new ArrayList<Local_Account>();

		File f = new File(context.getFilesDir() + FileDir.ACCOUNTS_PASSWORDS_FILE2);

		// 文件的长度，byte为单位
		int flength;

		if (f.exists()) {

			flength = (int) f.length();

			if (flength == 0)
				return accounts;

			byte[] plain_bytes;

			byte[] encrypted_bytes = new byte[flength + 10];

			try {

				FileInputStream reader = new FileInputStream(f);
				String Acct_Array[] = null;
				int n;
				n = reader.read(encrypted_bytes, 0, encrypted_bytes.length);

				if (n != -1) {

					plain_bytes = SE.getInstance().decrypt(encrypted_bytes, 0, n);
					Log.e("AccHelpplain_bytes","AccHelpplain_bytes"+plain_bytes);
					String temp_accts = new String(plain_bytes, "utf-8");

					if (temp_accts != null && !"".equals(temp_accts)) {
						Acct_Array = temp_accts.split(",");

						if (Acct_Array != null && Acct_Array.length > 0) {
							for (int i = 0; i < Acct_Array.length; i++) {
								String temp = Acct_Array[i];
								String act[] = temp.split(":");

								Local_Account acct = new Local_Account();

								acct.username = act[0];
								acct.password = act[1];

								// 用户之前没有要求记录密码
								if (acct.password.trim().equals("null"))
									acct.password = "";

								acct.isValid = Integer.parseInt(act[2]);
								acct.last_login_time = Long.parseLong(act[3]);

								if (valid_only) {
									// 只将有效的账号放入list中
									if (acct.isValid == ACCOUNT_VALID) {
										accounts.add(acct);
										Log.d("AccoutHelper","getLocalAccountsAsArrayList(valid) - "
												+ acct.toString());
									}
								} else {
									accounts.add(acct);
									Log.d("AccoutHelper","getLocalAccountsAsArrayList(all) - "
											+ acct.toString());
								}

							}

						}
					}

				}

				reader.close();

			} catch (Exception e) {
				e.printStackTrace();
				// Logger.print_red("getLocalAccountsAsArrayList(。。。。)- ",e.getLocalizedMessage());
			}

		}

		return accounts;

	}

	public static class Local_Account implements Comparable<Local_Account> {
		public String username = "";
		public String password = "";
		public int isValid = 1;
		public long last_login_time = 0;

		public Local_Account() {
		}

		public Local_Account(String u, String p) {
			username = u;
			password = p;
		}

		public Local_Account(String u, String p, int v) {
			username = u;
			password = p;
			isValid = v;
		}

		public Local_Account(String u, String p, int v, long t) {
			username = u;
			password = p;
			isValid = v;
			last_login_time = t;
		}

		@Override
		public String toString() {
			return "username=" + username + ",password=" + password + ",valid="
					+ isValid + ",last_login_time=" + last_login_time;
		}

		@Override
		public int compareTo(Local_Account another) {

			return (this.last_login_time < another.last_login_time) ? -1
					: ((this.last_login_time == another.last_login_time) ? 0
							: 1);
		}

		public boolean isEmpty() {
			return "".equals(username) || "".equals(password);
		}

	}

}
